import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import authApi from '@/api/authApi.js';
import toolLogin from '@/utils/login.js';

export const useUserStore = defineStore('user', () => {
	const token = ref(uni.getStorageSync('token') || '')
	const user = ref(uni.getStorageSync('userInfo') || {})

	const setToken = (val) => {
		token.value = val
		uni.setStorageSync('token', val)
	}

	const setUser = (val) => {
		user.value = val
		uni.setStorageSync('userInfo', val)
	}

	const HLogin = (encryptedData, iv) => {
		uni.login({
			provider: 'weixin',
			success: function(res) {
				const params = {
					code: res.code,
					encryptedData,
					iv
				};
				authApi.login(params).then((res) => {
					console.log('authApi.login', res);
					setToken(res.data);

					// HGetWxUserInfo()

					authApi.info().then(user => {
						setUser(user.data);

						toolLogin.loginGoback()
					})
				});
			}
		});
	}

	const HGetUserInfo = () => {
		authApi.info().then(user => {
			setUser(user.data);
		})
	}

	function HGetWxUserInfo() {
		wx.login({
			success: function(res) {
				console.log(res.code);
				// 发送 res.code 到后台换取 openId, sessionKey, unionId
				wx.getUserInfo({
					success: function(res2) {
						const params = {
							encryptedData: res2.encryptedData,
							iv: res2.iv,
							code: res.code
						}
						authApi.getWxUserInfo(params).then(res3 => {
							console.log('authApi.getWxUserInfo', res3);
							// setToken(res.data);
							// authApi.info().then(user => {
							// 	setUser(user.data);
							// }
							// }
						})
					}
				})
			},
		})
	}

	return {
		token,
		user,
		HLogin,
		HGetUserInfo
	}
})